package org.chen.controller;

import org.chen.model.dto.SysConfigDTO;
import org.chen.model.sys.SysConfig;
import org.chen.response.PageResult;
import org.chen.response.Result;
import org.chen.service.impl.ConfigServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/config")
public class ConfigController {
    @Autowired
    private ConfigServiceImpl configService;

    @GetMapping
    public Result<PageResult<SysConfig>> getConfigList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String key,
            @RequestParam(required = false) String category) {

        PageResult<SysConfig> result = configService.getConfigList(page, size, key, category);
        return Result.success(result);
    }

    @PostMapping
    public Result<Void> addConfig(@RequestBody @Validated SysConfigDTO configDTO) {
        configService.addConfig(configDTO);
        return Result.success();
    }

    @PutMapping("/{key}")
    public Result<Void> updateConfig(
            @PathVariable String key,
            @RequestBody @Validated SysConfigDTO configDTO) {
        configDTO.setConfigKey(key);
        configService.updateConfig(configDTO);
        return Result.success();
    }

    @GetMapping("/{key}")
    public Result<String> getConfig(@PathVariable String key) {
        return Result.success(configService.getConfigValue(key));
    }

    @DeleteMapping("/{key}")
    public Result<Void> deleteConfig(@PathVariable String key) {
        configService.deleteConfig(key);
        return Result.success();
    }
}
